package nobnak.study.gl.projection;

import java.util.Arrays;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;

public class RasterizationUtil {
	public static final int L_MAX = 255;
	public static final int L_MIN = 0;	
	
	public static Bitmap rasterize(Triangle[] triangles, int width, int height, float[] vpvMatrix, ProgressListener listener) {
		Triangle[] triangleRastered = new Triangle[triangles.length];
		for (int i = 0; i < triangles.length; i++)
			triangleRastered[i] = triangles[i].muliply(vpvMatrix, 0);

		int[] framebuffer = new int[width * height];
		float[] depthbuffer = new float[width * height];
		Arrays.fill(depthbuffer, Float.POSITIVE_INFINITY);
		float[] outUv = new float[2];
		float[] outP  = new float[3];
		int total = width * height;
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				int position = x + y * width;
				listener.onStart(position, total);
				for (int t = 0; t < triangleRastered.length; t++) {
					Triangle tri = triangleRastered[t];
					if (!tri.hit(outP, outUv, x, y))
						continue;
					if (depthbuffer[position] < outP[2])
						continue;
					
					framebuffer[position] = tri.bilinear(outUv[0], outUv[1]);
					depthbuffer[position] = outP[2];
				}
				listener.onEnd(position, total);
			}
		}
		return Bitmap.createBitmap(framebuffer, width, height, Config.ARGB_8888);
	}
	
	// Interfaces
	public static interface ProgressListener {
		void onStart(int position, int total);
		void onEnd(int position, int total);
	}
}
